<template>
  <div class="login-container">
    <h2 class="title">用户登录</h2>
    <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginFormRef"
        class="login-form"
        @submit.prevent="handleSubmit"
        label-width="100px"
    >
      <el-form-item
          prop="username"
          label="用户名"
          class="form-item"
      >
        <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            required
            prefix-icon="el-icon-user"
        />
      </el-form-item>
      <el-form-item
          prop="password"
          label="密码"
          class="form-item">
        <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            type="password"
            required
            prefix-icon="el-icon-lock"
        />
      </el-form-item>
      <el-button type="primary" class="login-button" @click="handleSubmit">登录</el-button>
      <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
    </el-form>
    <!-- 新增一行未注册，可以跳转注册页 -->
    <p class="register-link">
      没有账号？
      <a @click="navigateToRegister">立即注册</a>
    </p>
  </div>
</template>

<script>
import {ref} from 'vue';
import {useRouter} from 'vue-router';
import {loginUser} from '@/api/auth';

export default {
  name: 'UserLogin',
  setup(props, {emit}) {
    const loginFormRef = ref(null);
    const loginForm = ref({
      username: '',
      password: '',
    });
    const errorMessage = ref('');

    const rules = {
      username: [
        {required: true, message: '请输入用户名', trigger: 'blur'},
        {min: 4, max: 20, message: '用户名长度应为4-20个字符', trigger: 'blur'},
        {
          pattern: /^[a-zA-Z0-9_]+$/,
          message: '用户名只能包含字母、数字和下划线',
          trigger: 'blur',
        },
      ],
      password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 8, max: 20, message: '密码长度应为8-20个字符', trigger: 'blur'},
        {
          pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/,
          message:
              '密码必须包含至少一个大写字母、一个小写字母、一个数字和一个特殊字符',
          trigger: 'blur',
        },
      ],
    };

    const router = useRouter();

    const handleSubmit = async () => {
      try {
        await loginFormRef.value.validate(); // 触发表单验证
        const response = await loginUser(loginForm.value);
        // 登录成功后存储用户信息
        localStorage.setItem('user', JSON.stringify(response.data));
        // 通知父组件用户信息已更新
        emit('userLoggedIn', response.data);
        // 跳转到首页或其他页面
        router.push('/');
        errorMessage.value = '';
      } catch (error) {
        // 检查后端返回的错误信息
        if (error.response && error.response.data && error.response.data.error === 'Invalid credentials') {
          errorMessage.value = '用户名或密码错误';
        } else if (error.message) {
          errorMessage.value = error.message;
        } else {
          errorMessage.value = '登录失败，请检查用户名或密码';
        }
      }
    };

    const navigateToRegister = () => {
      // 跳转到注册页面
      router.push('/register');
    };

    return {
      loginForm,
      loginFormRef,
      errorMessage,
      handleSubmit,
      rules,
      navigateToRegister,
    };
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 100px; /* 调整顶部内边距，使内容靠近上边缘 */
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.title {
  text-align: center;
  color: #fff;
  margin-bottom: 20px;
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 20px; /* 调整每个表单项的间距 */
}

.login-button {
  width: 100%;
  margin-top: 20px;
}

.error-message {
  color: #f56c6c;
  text-align: center;
  margin-top: 10px;
}

.register-link {
  margin-top: 20px;
  text-align: center;
}

.register-link a {
  color: #409EFF;
  cursor: pointer;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>